# coding = utf-8
from django.db.models import Q
from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from base.models import CustomSupplier, CustSuppClass, StoreHouse, AccountTitle
from .mobile_serializers import MobileCustomSupplierSerializer, MobileCustSuppClassSerializer, \
    MobileStoreHouseSerializer, MobileAccountTitleSerializer


class MobileCustSuppClassListView(ListAPIView):
    """客商分类"""
    authentication_classes = ()
    permission_classes = ()
    queryset = CustSuppClass.objects.filter(parent__isnull=True)
    serializer_class = MobileCustSuppClassSerializer
    pagination_class = None


class MobileCustomerViewSet(ModelViewSet):
    """客户"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = CustomSupplier.objects.filter(is_customer=1)
    serializer_class = MobileCustomSupplierSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(telephone__contains=name) | Q(help_code__contains=name))

        return queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data["is_customer"] = True
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class MobileStoreHouseListView(ListAPIView):
    """仓库表"""
    permission_classes = ()
    queryset = StoreHouse.objects.all()
    serializer_class = MobileStoreHouseSerializer
    pagination_class = None


class MobileAccountTitleListView(ListAPIView):
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = AccountTitle.objects.filter(parent__isnull=True)
    serializer_class = MobileAccountTitleSerializer
